package com.liu.designmode.proxy;

import com.liu.designmode.service.iface.OrderService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy implements InvocationHandler {

    private Object target;

    public JDKProxy(Object o) {
        this.target = o;
    }

    public <T> T getProxy(Class<T> clz) {
        return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, this);
    }

    public Object getProxy(OrderService orderService) {
        // 匿名内部类的写法，这样可以直接写在工厂中，直接增强被代理类（接口）的方法
//        return Proxy.newProxyInstance(
//                orderService.getClass().getClassLoader(),
//                orderService.getClass().getInterfaces(),
//                (proxy, method, args) -> {
//                    System.out.println("before...");
                      // target必须是某接口的具体实现类
//                    Object result = method.invoke(orderService, args);
//                    System.out.println("after...");
//                    return result;
//                }
//        );

        // 和上面的代码是等价的
        return Proxy.newProxyInstance(
                orderService.getClass().getClassLoader(),
                orderService.getClass().getInterfaces(),
                this
        );
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before...");
        // target必须是某接口的具体实现类
        Object result = method.invoke(target, args);
        System.out.println("after...");
        return result;
    }

}
